﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Buddy.Samples
{
    static partial class Program
    {
        static void Samples_Structs()
        {
            var dataBytes = new byte[7];
            for (int i = 0; i < dataBytes.Length; i++) dataBytes[i] = Convert.ToByte(0xFF - i);

            var sample = new Sample();
            sample.Name = "KAVEH";
            sample.Tracking = dataBytes;
            sample.User = 1;

            Console.WriteLine(sample);
            var bytes = sample.FromStruct();
            Console.WriteLine("#{0,-5}: {1}", bytes.Length, bytes.BinaryText());
            sample = bytes.ToStruct<Sample>();
            Console.WriteLine(sample);

            Console.WriteLine("press any key to continue ...");
            Console.ReadKey();
        }
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Sample
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
        public string Name;

        [MarshalAs(UnmanagedType.U4)]
        public uint User;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]
        public byte[] Tracking;

        public override string ToString()
        {
            return new
            {
                Name = Name,
                User = User,
                Tracking = Tracking.BinaryText()
            }.ToString();
        }
    }
}
